package cn.redragon.soa.common.dto;

import static java.util.stream.Collectors.toList;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.domain.Page;

@Getter
@Setter
@ToString
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor
public class PageResultDTO<T> {

    private long total;
    private int totalPages;
    private int size;
    private int page;

    private List<T> result;

    public static <T> PageResultDTO<T> empty() {
        return new PageResultDTO<>(0L, 0, 0, 0, Collections.emptyList());
    }

    public static <T> PageResultDTO<T> of(Page<T> page) {
        return PageResultDTO.of(page, page.getContent());
    }

    public static <T, I> PageResultDTO<T> of(Page<I> page, Function<I, T> recordHandler) {
        List<T> list = page.getContent().stream().map(recordHandler).collect(toList());

        return PageResultDTO.of(page, list);
    }

    public static <T, I> PageResultDTO<T> of(Page<I> page, List<T> list) {
        return PageResultDTO.of(
            page.getTotalElements(),
            page.getTotalPages(),
            page.getPageable().getPageSize(),
            page.getPageable().getPageNumber() + 1,
            list);
    }

    public static <T> PageResultDTO<T> of(long total, int totalPages, int size, int page, List<T> result) {
        return new PageResultDTO<>(total, totalPages, size, page, result);
    }

}
